<template>
  <div class="app-container">
    <avue-crud
      :key="showTable"
      :option="option"
      :data="data"
      :table-loading="loading"
      @tree-load="load"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @current-change="currentChange"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="resetChange"
    >
      <template
        slot="deptValue"
        slot-scope="scope"
      >
        <span>
          <i
            style="font-size: 14px;"
            v-if="scope.row.iconCls"
            :class="scope.row.iconCls"
          ></i>
          {{scope.row.deptValue}}
        </span>
      </template>
    </avue-crud>
  </div>
</template>

<script>
import { addOrg, upOrg, getOrg, delOrg } from '@/api/user.js'
import iconList from '@/utils/iconList'
export default {
  data() {
    return {
      loading: false,
      showTable: true,
      /* 分页 */
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        text: '',
        background: false,
      },
      data: [],
      tableDataCopy: [],
      officeList: [],
      searchList: {},
      option: {
        height: 700,
        headerAlign: 'center',
        dialogMenuPosition:'center',
        align: 'center',
        border: true,
        index: true,
        lazy: true,
        indexLabel: '序号',
        indexWidth: 100,
        card: true,
        rowKey: 'id',
        defaultExpandAll: false,
        dialogDrag: false,
        searchMenuSpan: 4,
        searchSpan: 6,
        searchLabelWidth: '25%',
        column: [
          {
            label: '机构名称',
            align: 'left',
            prop: 'deptValue',
            width: 350,
            search: true,
            searchPlaceholder: '请输入机构名称',
            overHidden: true,
            rules: [
              { required: true, message: '请输入机构名称', trigger: 'blur' },
            ],
          },
          {
            label: '机构类型',
            prop: 'deptType',
            type: 'select',
            dicData: [],
            rules: [
              { required: true, message: '请选择机构类型', trigger: 'change' },
            ],
          },
          {
            label: '上级机构',
            prop: 'deptPid',
            type: 'tree',
            defaultExpandAll: true,
            expandOnClickNode: false,
            dicData: [
              {
                deptValue: '全部',
                id: 'R',
                children: [],
              },
            ],
            props: {
              label: 'deptValue',
              value: 'id',
            },
            rules: [
              {
                required: true,
                message: '请选择上级机构',
                trigger: 'change',
              },
            ],
          },
          /* {
                            label: '排序',
                            prop: 'deptOrder',
                            type: 'number',
                            value: 0,
                            width: 80
                        },
                        {
                            label: '负责人',
                            prop: 'position',
                        },
                        {
                            label: '职能',
                            prop: 'manager',
                        },
                        {
                            label: '自定义图标',
                            prop: 'iconCls',
                            type: "icon",
                            iconList: [{
                                label: '通用图标',
                                list: iconList
                            }],
                            hide: true
                        }, */
          /* {
                            label: '创建时间',
                            prop: 'createTime'
                        }, */
          // {
          //     label: '备注',
          //     prop: 'deptDesc',
          //     type: 'textarea',
          //     span: 24
          // }
          {
            label: '组织ID',
            prop: 'id',
            display: false,
          },
        ],
      },
    }
  },
  created() {
    this.$store
      .dispatch('asyncApi/getDict', {
        code: 'JGLX',
      })
      .then((res) => {
        this.option.column[1].dicData = res
      })
      this.onLoad()
    this.getOfficeList()
  },
  methods: {
    onLoad(page, params = {}) {
      /* if (page.layout) {
                    Object.assign(params, {
                        page: this.page.currentPage,
                        size: this.page.pageSize,
                    });
                } else {
                    page.deptValue ? page['text'] = page.deptValue : page['text'] = ''
                    Object.assign(params, page);
                } */
      let searchList = this.searchList
      Object.assign(params, {
        ...searchList,
        text: searchList.deptValue,
        page: 1,
        size: 1000000,
      })

      this.loading = true
      getOrg(params).then((data) => {
        this.loading = false
        this.showTable = !this.showTable
        //this.data = data.data.records;
        this.page.total = data.data.total
        this.tableDataCopy = data.data.records || [] // 备份的全量数据
        this.data = JSON.parse(JSON.stringify(data.data.records)).map(
          (item) => {
            // 展示数据
            // hasChildren 表示需要展示一个箭头图标
            item.hasChildren = item.children && item.children.length > 0
            // 只展示一层
            // 如果有children数据，会自动加载，就不是懒加载了，也可以配置tree-props里面的children为其他字段
            item.children = null
            // 记住层级关系
            item.idList = [item.id]
            return item
          }
        )
      })
    },
    // 展开
    load(tree, treeNode, resolve) {
      // 层级关系备份
      const idCopy = JSON.parse(JSON.stringify(tree.idList))

      // 查找下一层数据
      let resolveArr = this.tableDataCopy
      let id
      // eslint-disable-next-line
      while ((id = tree.idList.shift())) {
        const tarItem = resolveArr.find((item) => item.id === id)
        tarItem.loadedChildren = true
        resolveArr = tarItem.children
      }

      // 处理下一层数据的属性
      resolveArr = JSON.parse(JSON.stringify(resolveArr))
      resolveArr.forEach((item) => {
        item.hasChildren = item.children && item.children.length > 0
        item.children = null
        // 此处需要深拷贝，以防各个item的idList混乱
        item.idList = JSON.parse(JSON.stringify(idCopy))
        item.idList.push(item.id)
      })

      // 标识已经加载子节点
      tree.loadedChildren = true

      // 渲染子节点
      resolve(resolveArr)
    },
    getOfficeList() {
      getOrg({ page: 1, size: 1000000 }).then((data) => {
        this.officeList = data.data.records
        this.pMenu()
      })
    },
    /* 清空 */
    resetChange() {
      /* this.page.currentPage = 1;
                this.page.pageSize = 10; */
      this.searchList = {}
      this.onLoad()
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      done()
      /* this.page.currentPage = 1;
                this.page.pageSize = 10; */
      this.searchList = {
        ...params,
      }
      this.onLoad()
    },
    /* 新增 */
    rowSave(row, done, loading) {
      addOrg(row).then(
        (data) => {
          done()
          this.onLoad()
          console.log(data)
          this.getOfficeList()
          // this.$message({
          //     type: "success",
          //     message: "操作成功!"
          // });
        },
        (error) => {
          window.console.log(error)
          loading()
        }
      )
    },
    /* 修改 */
    rowUpdate(row, index, done, loading) {
      delete row.createTime
      delete row.updateTime
      upOrg(row).then(
        () => {
          done()
          this.onLoad()
          this.getOfficeList()
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
        },
        (error) => {
          window.console.log(error)
          loading()
        }
      )
    },
    /* 改变页码 */
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    /* 删除 */
    rowDel(row) {
      this.$confirm(
        '该机构下若存在用户，删除该机构将同时删除该机构下所有用户，是否删除？',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        delOrg({
          id: row.id,
        }).then((res) => {
          if (res.status) {
            this.onLoad()
            this.getOfficeList()
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
          } else {
            this.$message.error(res.msg)
          }
        })
      })
    },
    /*匹配上级菜单*/
    pMenu() {
      let i = this.findArray(this.option.column, 'deptPid', 'prop')
      if (i > -1) {
        this.option.column[i].dicData[0].children = this.officeList
      }
    },
    /* 弹窗打开前 */
    beforeOpen(done, type) {
      if (['edit', 'add'].includes(type)) {
        let i = this.findArray(this.option.column, 'deptPid', 'prop')
        if (i > -1) {
          this.option.column[i].dicData[0].children = this.data
        }
      }
      done()
    },
  },
}
</script>

<style scoped="scoped" lang="scss">
/deep/ .avue-crud__pagination {
  text-align: center;
}
</style>
